using System;
using System.Collections;
using BitMango;
using BitMango.Diagnostics;
using UnityEngine;

public class DWATTHelper : MonoBehaviour
{
    public static string StageName
    {
        get
        {
            return DWATTHelper.stageName;
        }
    }

    public static string AdRevision
    {
        set
        {
            DWATTHelper.adRevision = value;
        }
    }

    public static string Prefix
    {
        set
        {
            DWATTHelper.prefix = value;
        }
    }

    public static float ElapseTime
    {
        get
        {
            return Time.time - DWATTHelper.sessionStartTime;
        }
    }

    public static string Version
    {
        get
        {
            return DWATTHelper.version;
        }
        set
        {
            DWATTHelper.version = value;
        }
    }

    private void Awake()
    {
        DWATTHelper.formatVersion = "2";
        DWATTHelper.appID = Context.BMPlatform.appID;
        DWATTHelper.OS = WWW.EscapeURL(SystemInfo.operatingSystem);
        DWATTHelper.deviceModel = WWW.EscapeURL(SystemInfo.deviceModel);
        DWATTHelper.storeType = Context.BMPlatform.storeType.ToString();
        base.StartCoroutine(DWATTHelper.SendLogQueue());
    }

    private void onStartSession()
    {
        Debugger.Log("DWATTHelper.onStartSession");
        DWATTHelper.sessionStartTime = Time.time;
    }

    private IEnumerator onEndSession()
    {
        Debugger.Log("DWATTHelper.onEndSession");
        float elapseTime = DWATTHelper.ElapseTime;
        float dailySessionTime = Profile.DailySessionTime;
        float accumSessionTime = Profile.AccumSessionTime;
        Profile.AccumSessionTime = accumSessionTime;
        Profile.AccumSessionCount++;
        Profile.DailySessionCount++;
        PlayerPrefs.Save();
        yield break;
    }

    private void Start()
    {
        Debugger.Log("DWATTHelper.Start");
        this.onStartSession();
    }

    private IEnumerator OnApplicationPause(bool pause)
    {
        if (pause)
        {
            if (DWATTHelper.loggingStageEvent)
            {
                PlayerPrefs.SetFloat("DWATT.cielp", Time.time - DWATTHelper.startTime);
            }
            yield return base.StartCoroutine(this.onEndSession());
        }
        else
        {
            this.onStartSession();
        }
        yield break;
    }

    private void OnApplicationQuit()
    {
        this.onEndSession();
    }

    public static void logEvent(string eventName, params object[] ps)
    {
        //if (Platform.IsEU())
        //{
        //    Debugger.Log("DWATTHelper.logEvent - Can't send log to EU users");
        //    return;
        //}
        //string text = "&e=" + WWW.EscapeURL(eventName);
        //string text2 = "DWATTHelper.logEvent:" + eventName;
        //for (int i = 0; i < ps.Length; i++)
        //{
        //    text += string.Format("&v{0}={1}", i + 1, (ps[i] != null) ? WWW.EscapeURL(ps[i].ToString()) : string.Empty);
        //    text2 += string.Format(" v{0}:{1}", i + 1, (ps[i] != null) ? ps[i].ToString() : string.Empty);
        //}
        //string url = (!(eventName == "impression")) ? DWATTHelper.analyticsLogURL : DWATTHelper.analytics2LogURL;
        //TaskManager.StartCoroutine(DWATTHelper.SendLog(url, text, false));
        //FirebaseAnalyticsHelper.logEvent(eventName, ps);
        //Debugger.Log(text2);
    }

    public static void startStageEvent(string stage)
    {
        if (PlayerPrefs.HasKey("DWATT.cielp"))
        {
            PlayerPrefs.DeleteKey("DWATT.cielp");
        }
        Debugger.Log(string.Concat(new object[]
        {
            "DWATTHelper.startStageEvent: ",
            stage,
            " T:",
            Time.time
        }));
        Debugger.Assert(!DWATTHelper.loggingStageEvent, "stageEvent can only one at a time! : " + DWATTHelper.stageName + ":" + stage);
        DWATTHelper.loggingStageEvent = true;
        DWATTHelper.stageName = stage;
        Profile.LastStageName = DWATTHelper.stageName;
        DWATTHelper.startTime = Time.time;
    }

    public static void endStageEvent(bool state, int starCount = -1, float narrowness = 0f)
    {
        Debugger.Log(string.Concat(new object[]
        {
            "DWATTHelper.endStageEvent : ",
            DWATTHelper.stageName,
            " T:",
            Time.time,
            "(",
            Time.time - DWATTHelper.startTime,
            ")"
        }));
        Debugger.Assert(DWATTHelper.loggingStageEvent, "First, call startStageEvent ");
        if (!DWATTHelper.loggingStageEvent)
        {
            return;
        }
        DWATTHelper.loggingStageEvent = false;
        float num = Time.time - DWATTHelper.startTime;
        if (!state)
        {
            starCount = -1;
        }
        DWATTHelper.logEvent("clearinfo", new object[]
        {
            (!state) ? "0" : "1",
            num.ToString(),
            DWATTHelper.stageName,
            starCount.ToString(),
            narrowness.ToString()
        });
        DWATTHelper.stageName = string.Empty;
        PlayerPrefs.DeleteKey("DWATT.cielp");
    }

    private static string EncodeWithKey(string text, string key)
    {
        byte[] array = new byte[text.Length];
        for (int i = 0; i < text.Length; i++)
        {
            array[i] = (byte)(text[i] ^ key[i % key.Length]);
        }
        return Convert.ToBase64String(array, 0, array.Length);
    }

    private static IEnumerator SendLog(string URL, string param, bool writeQueue)
    {
        if (Application.platform != RuntimePlatform.IPhonePlayer && Application.platform != RuntimePlatform.Android)
        {
            yield break;
        }
        if (Application.internetReachability == NetworkReachability.NotReachable)
        {
            Debugger.Log("DWATTHelper.SendLog NetworkReachability.NotReachable");
            if (writeQueue)
            {
                string text = PlayerPrefs.GetString("DWATTLogQueue");
                if (text != null && text != string.Empty && text[0].ToString() == "|")
                {
                    text = text.Remove(0, 1);
                }
                string[] array = text.Split(new char[]
                {
                    '|'
                });
                if (array.Length < 100)
                {
                    PlayerPrefs.SetString("DWATTLogQueue", text + param + "|");
                    PlayerPrefs.Save();
                }
            }
            yield break;
        }
        string appsFlyerId = "none";
        string ua_campaign_name = "none";
        string logParam = string.Concat(new string[]
        {
            "log.xlg?a=",
            DWATTHelper.appID,
            "&u=",
            Profile.UUID,
            "&aid=",
            Profile.ADID,
            "&v=",
            DWATTHelper.version,
            DWATTHelper.prefix,
            "&f=",
            DWATTHelper.formatVersion,
            "&s=",
            DWATTHelper.storeType,
            "&o=",
            DWATTHelper.OS,
            "&d=",
            DWATTHelper.deviceModel,
            "&it=",
            Profile.InstallTimeStr,
            "&iv=",
            Profile.InstallVersion,
            DWATTHelper.prefix,
            "&ar=",
            DWATTHelper.adRevision,
            "&afid=",
            appsFlyerId,
            "&c=",
            ua_campaign_name
        });
        Debugger.Log("DWATTHelper.SendLog logParam : " + logParam + " Param : " + param);
        WWW wwwLog = new WWW(string.Concat(new string[]
        {
            URL,
            logParam,
            param,
            "&ts=",
            WWW.EscapeURL(DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd HH:mm:ss") + " GMT")
        }));
        yield return wwwLog;
        Debugger.Log("DWATTHelper.SendLog result : " + wwwLog.error);
        yield break;
    }

    private static IEnumerator SendLogQueue()
    {
        for (; ; )
        {
            if (Application.internetReachability != NetworkReachability.NotReachable)
            {
                string text = DWATTHelper.PopLogQueue();
                if (text != null && text != string.Empty)
                {
                    DWATTHelper.DeleteLogQueue(text);
                  //  TaskManager.StartCoroutine(DWATTHelper.SendLog(DWATTHelper.analyticsLogURL, text, true));
                }
            }
            yield return new WaitForSeconds(1.5f);
        }
        yield break;
    }

    private static string PopLogQueue()
    {
        string @string = PlayerPrefs.GetString("DWATTLogQueue");
        if (@string.Length > 0)
        {
            Debugger.Log("DWATTLogQueue:" + @string);
        }
        if (@string != string.Empty)
        {
            string[] array = @string.Split(new char[]
            {
                '|'
            });
            return array[0];
        }
        return null;
    }

    private static void DeleteLogQueue(string log)
    {
        string @string = PlayerPrefs.GetString("DWATTLogQueue");
        if (@string != string.Empty)
        {
            string value = @string.Replace(log + "|", string.Empty);
            PlayerPrefs.SetString("DWATTLogQueue", value);
        }
    }

    public static void logItemUse(string item, int count, int total, string where)
    {
        DWATTHelper.logEvent("UncleBill.Use", new object[]
        {
            item,
            count.ToString(),
            total.ToString(),
            Profile.LastStageName,
            where
        });
    }

    public static void logItemBuy(string item, int count, int total, string where)
    {
        DWATTHelper.logEvent("UncleBill.Buy", new object[]
        {
            item,
            count.ToString(),
            total.ToString(),
            Profile.LastStageName,
            where
        });
    }

    public static void logItemEarn(string item, int count, int total, string where)
    {
        DWATTHelper.logEvent("UncleBill.Earn", new object[]
        {
            item,
            count.ToString(),
            total.ToString(),
            Profile.LastStageName,
            where
        });
    }

    private static string appID;

    private static string version;

    private static string OS;

    private static string deviceModel;

    private static string formatVersion;

    private static float startTime;

    private static string stageName = string.Empty;

    private static string storeType;

    public static float sessionStartTime;

    private static string prefix = string.Empty;

    private static string adRevision = string.Empty;

    private static bool loggingStageEvent;

    //private static string analyticsLogURL = "https://a.bitmango.com/";

    //private static string analytics2LogURL = "https://a2.bitmango.com/";
}
